package com.team2.cyber_eye.background_task;

import java.util.ArrayList;

import android.app.Activity;
import android.os.AsyncTask;

import com.team2.cyber_eye.ActivityHelpers.Util;
import com.team2.shared.CyberServer;
import com.team2.shared.Product;
import com.team2.shoppingService.Server;

public class BackgroundTask extends AsyncTask<ArrayList<String>, Integer, ArrayList<ArrayList<Product>> > {

	public interface LoadingTaskFinishedListener {
		void onTaskFinished(ArrayList<ArrayList<Product>> products); // If you want to pass something back to the listener add a param to this method
	}

	// This is the progress bar you want to update while the task is in progress
	// This is the listener that will be told when this task is finished
	private final LoadingTaskFinishedListener finishedListener;
	private final Activity creator;
	/**
	 * A Loading task that will load some resources that are necessary for the app to start
	 * @param progressBar - the progress bar you want to update while the task is in progress
	 * @param finishedListener - the listener that will be told when this task is finished
	 */
	public BackgroundTask(LoadingTaskFinishedListener finishedListener, Activity creator)
	{
		this.finishedListener = finishedListener;
		this.creator = creator;
	}


	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		
	}

	@Override
	protected void onPostExecute(ArrayList<ArrayList<Product>> result) {
		super.onPostExecute(result);
		finishedListener.onTaskFinished(result); // Tell whoever was listening we have finished
	}

	@Override
	protected ArrayList<ArrayList<Product>> doInBackground(ArrayList<String>... params) {
		try
		{
			ArrayList<ArrayList<Product>> products = new ArrayList<ArrayList<Product>>();
			
			CyberServer cyberserver =  new Server();
			String searchText = params[0].get(0);
			String category = params[0].get(1);
			String fromIQE = params[0].get(2);
			String iqeOrBarcode = params[0].get(3);
			String filePath = params[0].get(4);
			
			ArrayList<Product> localStoreProducts;
			ArrayList<Product> onlineProducts;
			
			if(fromIQE.equals("yes") && iqeOrBarcode.equals("iqe")){
				localStoreProducts = cyberserver.searchProducts(searchText, filePath, category, true);
				onlineProducts = cyberserver.searchOnlineProducts(searchText, category, filePath);
			}else {
				localStoreProducts = cyberserver.searchProductsWithCategory(searchText, category);
				onlineProducts = cyberserver.searchOnlineProducts(searchText, category);
			}
			
			products.add(onlineProducts);
			products.add(localStoreProducts);
			
			return products;
		}
		catch (Exception ex)
		{
			//DONT DISPLAY ERRORS THEY DO NOT WORK
			Util.LogError(ex);
			return null;
		}
	}
}
